import 'package:dio/dio.dart';
import 'package:flutter_app_open_camera/constant/Constants.dart';
import 'package:flutter_app_open_camera/generated/json/base/json_convert_content.dart';

import 'package:flutter_app_open_camera/net/utils/AuthInterceptor.dart';
import 'package:flutter_app_open_camera/net/utils/ErrorInterceptor.dart';
import 'package:flutter_app_open_camera/utils/loading_utils.dart';

import 'entity/BaseResp.dart';

class NetWorkManager {
  factory NetWorkManager() => _getInstance();

  static NetWorkManager get instance => _getInstance();
  static NetWorkManager _instance;
  Dio dio;
  BaseOptions options;

  NetWorkManager._internal() {
    dio = Dio()
      ..options = BaseOptions(
          baseUrl: Constants.BASE_URL,
          connectTimeout: 10000,
          receiveTimeout: 1000 * 60 * 60 * 24,
          responseType: ResponseType.json,
          headers: {"Content-Type": "application/json"})
      //网络状态拦截
      ..interceptors.add(AuthInterceptor())
      ..interceptors.add(HttpLog())
      ..interceptors.add(ErrorInterceptor());
  }

  static NetWorkManager _getInstance() {
    if (_instance == null) {
      _instance = new NetWorkManager._internal();
    }
    return _instance;
  }

  ///post请求
  static post<T>(String url, data, Function(T map) onSuccess,
      {Function(BaseResp error) onError}) async {
    try {
      var response = await NetWorkManager.instance.dio
          .post(Constants.BASE_URL + url, data: data);
      if (response.statusCode != 200) {
        Loading.showLoading(false);
        onError(BaseResp(code: 500, msg: '网络错误', data: ''));
        return;
      }
      String body = response.toString();
      BaseResp resp = baseRespFromJson(body);
      if (resp.code == Constants.OK) {
        if (resp.data != null) {
          Map data = new Map<String, dynamic>.from(resp.data);
          onSuccess(JsonConvert.fromJsonAsT<T>(data));
        } else {
          onSuccess(null);
        }
      } else {
        Loading.showLoading(false);
        onError(resp);
      }
    } catch (e) {
      print("--" * 20);
      print(e);
      print('sdsdasdasdsa:  ' + e.toString());
      Loading.showLoading(false);
      Loading.showToast("网络错误");
    }
  }

  ///get请求
  static get<T>(String url, Map<String, dynamic> queryParameters,
      Function(T map) onSuccess,
      {Function(BaseResp error) onError}) async {
    var response = await NetWorkManager.instance.dio
        .get(Constants.BASE_URL + url, queryParameters: queryParameters);
    if (response.statusCode != 200) {
      Loading.showLoading(false);
      onError(BaseResp(code: 500, msg: '网络错误', data: ''));
      return;
    }
    String body = response.toString();
    BaseResp resp = baseRespFromJson(body);
    if (resp.code == Constants.OK) {
      Map data = new Map<String, dynamic>.from(resp.data);
      onSuccess(JsonConvert.fromJsonAsT<T>(data));
    } else {
      Loading.showLoading(false);
      onError(resp);
    }
  }
}
